﻿using System;
using System.Linq;
using System.Web.Mvc;
using mBlog.Services;
using mBlog.ViewModels;
using mBlog.Extensions;

namespace mBlog.Controllers
{
    public class CategoryController : BaseController
    {

        private ICategoryService categoryService;
        private IPostService postService;

        public CategoryController(ICategoryService categoryService, IPostService postService)
        {
            this.categoryService = categoryService;
            this.postService = postService;
        }


        public new ActionResult View(string urlName)
        {

            int? page = null;

            if (!string.IsNullOrEmpty(Request.QueryString["page"]))
                page = int.Parse(Request.QueryString["page"]);

            var posts = postService.GetByCategory(urlName, page, ItemsPerPage)
                .OrderByDescending(p => p.PublishedTime).ToList();


            ListView<PostView> listView = new ListView<PostView>
                                              {
                                                  Title = categoryService.Single(urlName).Name,
                                                  List = (from p in posts
                                                          select new PostView()
                                                                     {
                                                                         Post = p.MapTo<PostDetail>(),
                                                                         Categories =
                                                                             p.Categories.MapTo<CategoryDetail>(),
                                                                         Tags = p.Tags.MapTo<TagDetail>()
                                                                     }).ToList()
                                              };

            PagerView pager = new PagerView
                                  {
                                      ActionName = "View",
                                      ControllerName = "Category",
                                      CurrentPage = page ?? 0,
                                      PageCount =
                                          (int)Math.Ceiling((decimal) categoryService.GetPostTotalUnderCategory(urlName)/
                                                       ItemsPerPage)
                                  };

            listView.Pager = pager;

            return View(listView);
        }

    }
}
